// import { parallelLimit } from "async";

/*
function parallelLimit(tasks, limit) {
    if (!Array.isArray(tasks)) {
        throw new Error("First argument must be an array of tasks");
    }
    if (typeof limit !== "number" || limit < 1) {
        throw new Error("Second argument must be a positive number");
    }

    let results = [];
    let remaining = tasks.length;
    let running = 0;

    function taskCallback(err, result) {
        if (err) {
            // 如果有错误，拒绝Promise
            return Promise.reject(err);
        }
        results.push(result);
        running--;
        remaining--;
        nextTask();
    }

    function nextTask() {
        if (remaining === 0) {
            // 所有任务都已完成，解决Promise
            return Promise.resolve(results);
        }
        for (let i = 0; i < limit && running < limit && i < tasks.length; i++) {
            const task = tasks.shift();
            running++;
            Promise.resolve(task(taskCallback))
                // .then(taskCallback)
                // .then(task(taskCallback))
                .catch((error) => {
                    // 如果任务执行中有错误，减少running计数器并拒绝Promise
                    running--;
                    return Promise.reject(error);
                });
        }
    }

    nextTask(); // 启动任务

    return new Promise((resolve, reject) => {
        Promise.resolve().then(() => {
            try {
                nextTask();
            } catch (error) {
                reject(error);
            }
        });
    });
}
*/
function parallelLimit(tasks, limit) {
    const results = [];
    let taskIndex = 0;
    let runningCount = 0;

    function executeTask() {
        if (taskIndex < tasks.length) {
            runningCount++;
            const task = tasks[taskIndex++];
            const promise = new Promise((resolve, reject) => {
                Promise.resolve(task()).then(resolve).catch(reject);
            });

            promise
                .then((result) => {
                    results.push(result);
                    runningCount--;
                    if (results.length === tasks.length) {
                        // 所有任务完成
                        console.log("All tasks completed with results:", results);
                    }
                    executeTask(); // 继续执行下一个任务
                })
                .catch((error) => {
                    console.error("Task failed:", error);
                    runningCount--;
                    executeTask(); // 继续执行下一个任务
                });
        }
    }

    while (runningCount < limit) {
        executeTask();
        runningCount++;
    }

    // 返回一个Promise，以便可以链式调用.then()或.catch()
    return new Promise((resolve, reject) => {
        resolve(results);
    });
}

// 使用示例
// const tasks = [
//     function (callback) {
//         setTimeout(function () {
//             callback(null, "one");
//         }, 300);
//     },
//     function (callback) {
//         setTimeout(function () {
//             callback(null, "three");
//         }, 50);
//     },
//     function (callback) {
//         setTimeout(function () {
//             callback(null, "two");
//         }, 100);
//     },
// ];
const tasks = [
    () => new Promise((resolve) => setTimeout(resolve, 1000, "result 1")),
    () => new Promise((resolve) => setTimeout(resolve, 2000, "result 2")),
    () => new Promise((resolve) => setTimeout(resolve, 500, "result 3")),
];

// async
//     .parallelLimit(tasks, 2)
parallelLimit(tasks, 2)
    .then((results) => {
        console.log("All tasks completed with results:", results);
    })
    .catch((error) => {
        console.error("An error occurred:", error);
    });
